package role_authority

import (
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/model"
	"errors"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type RoleAuthorityRepository interface {
	base.Repository

	// 根据 roleId 获取相关权限
	FindByRoleId(roleId primitive.ObjectID) (*model.RoleAuthorities, error)
	// 更新角色权限
	UpdateByRoleId(role *model.Role) error
	// 删除角色权限
	DeleteByRoleId(roleId primitive.ObjectID) error
	// 批量删除角色权限
	BatchDeleteByRoleIds(roleIds []string) error
}

func NewRoleAuthorityRepository() RoleAuthorityRepository {
	return &roleAuthorityRepository{
		base.RepositoryStruct{
			CollectionName: server.RoleAuthorityCollectionName,
		},
	}
}

type roleAuthorityRepository struct {
	base.RepositoryStruct
}

func (ra *roleAuthorityRepository) FindByRoleId(roleId primitive.ObjectID) (*model.RoleAuthorities, error) {
	if roleId.IsZero() {
		return nil, errors.New("RoleId is zero.")
	}

	if err := ra.CheckDB(); err != nil {
		return nil, err
	}
	filter := bson.M{
		"roleId": roleId.Hex(),
	}
	roleAuthority := &model.RoleAuthorities{}
	err := ra.Mongo.FindMany(ra.CollectionName, filter, roleAuthority)
	return roleAuthority, err
}

func (ra *roleAuthorityRepository) UpdateByRoleId(role *model.Role) error {
	if role.Id.IsZero() || role.Type == "" {
		return errors.New("RoleId and roleType is required")
	}
	if err := ra.CheckDB(); err != nil {
		return err
	}
	// 删除角色所有权限
	err := ra.DeleteByRoleId(role.Id)
	if err != nil {
		return err
	}
	// 添加角色权限
	//role.Authorities.
	if role.Type == model.BackRole {
		if role.Authorities == nil {
			return errors.New("Authorities can not be null.")
		}
		if len(role.Authorities) == 0 {
			return nil
		}
		data := make([]interface{}, len(role.Authorities))
		for k := range role.Authorities {
			data[k] = &model.RoleAuthority{
				RoleId:        role.Id.Hex(),
				AuthorityName: role.Authorities[k],
				Type:          model.BackAuth,
			}
		}
		_, err = ra.Mongo.InsertMany(ra.CollectionName, data)
	} else if role.Type == model.AppRole {
		data := make([]interface{}, 0)
		if len(role.AppAuths) > 0 {
			for k := range role.AppAuths {
				data = append(data, &model.RoleAuthority{
					RoleId:        role.Id.Hex(),
					AuthorityName: role.AppAuths[k],
					Type:          model.AppAuth,
				})
			}
		}
		if len(role.FormAuths) > 0 {
			for k := range role.FormAuths {
				if len(role.FormAuths[k]) > 0 {
					for _, s := range role.FormAuths[k] {
						data = append(data, &model.RoleAuthority{
							RoleId:        role.Id.Hex(),
							AuthorityName: s,
							Type:          model.AppAuth,
							FormId:        k,
						})
					}
				}
			}
		}
		_, err = ra.Mongo.InsertMany(ra.CollectionName, data)
	} else {
		return errors.New("Auth type error")
	}
	return err
}

func (ra *roleAuthorityRepository) DeleteByRoleId(roleId primitive.ObjectID) error {
	if roleId.IsZero() {
		return errors.New("RoleId is zero.")
	}
	if err := ra.CheckDB(); err != nil {
		return err
	}
	// 删除角色所有权限
	filter := bson.M{
		"roleId": roleId.Hex(),
	}
	_, err := ra.Mongo.DeleteMany(ra.CollectionName, filter)
	return err
}

func (ra *roleAuthorityRepository) BatchDeleteByRoleIds(roleIds []string) error {
	if len(roleIds) == 0 {
		return nil
	}
	if err := ra.CheckDB(); err != nil {
		return err
	}
	filter := bson.M{
		"roleId": bson.M{
			"$in": roleIds,
		},
	}
	_, err := ra.Mongo.DeleteMany(ra.CollectionName, filter)
	return err
}
